export default function createCache(options: {mode: string} = {mode: ''}) {
    function isLocal(options: {mode: string}) {
        return (!options || !options.mode || options.mode === 'local');
    }

    function setItem(key: string, data: string, options: {mode: string}) {
        if (isLocal(options)) {
            localStorage.setItem(key, data);
        } else {
            sessionStorage.setItem(key, data);
        }
    }

    function getItem(key: string, options: {mode: string}): string {
        if (isLocal(options)) {
            return localStorage.getItem(key) || '';
        } else {
            return sessionStorage.getItem(key) || '';
        }
    }

    function removeItem(key: string, options: {mode: string}) {
        if (isLocal(options)) {
            localStorage.removeItem(key);
        } else {
            sessionStorage.removeItem(key);
        }
    }

    function set(key: string, data: any) {
        let val;
        if (typeof data == "object") {
            val = JSON.stringify(data);
        } else {
            val = data;
        }

        setItem(key, val, options);

        return data;
    }

    function get(key: string, def: any = undefined): any {
        const _value = getItem(key, options);
        if (_value) {
            let data: any;
            if (['{', '['].indexOf(_value.charAt(0)) != -1 && 
                ['}', ']'].indexOf(_value.charAt(_value.length - 1)) != -1) {
                data = JSON.parse(_value);
            } else {
                data = _value
            }
            return data;
        } else if (typeof def !== 'undefined') {
            set(key, def);
            return def;
        } else {
            return null;
        }
    }
    function remove(key: string) {
        const data = get(key);
        removeItem(key, options);
        return data;
    }

    return {
        set,
        get,
        remove,
        install(app: any) {
            if (isLocal(options)) {
                app.config.globalProperties.$cache = this;
                app.config.globalProperties.$localCache = this;
            } else {
                app.config.globalProperties.$sessionCache = this;
            }
        }
    };
}
